package tools.action.view {
	import kiwi.util.ArrayUtils;
	import kiwi.util.Tick;

	import tools.model.ActionFrameInfo;
	import tools.model.ActionInfo;

	import org.aswing.Container;

	import flash.display.Bitmap;
	import flash.display.Sprite;

	/**
	 * @author zhangming.luo
	 */
	public class ActionPreview extends Container {
		private var action : ActionInfo;
		private var last : int;
		private var unit : int = 1000 / 15;
		private var canvas : Bitmap;
		private var container : Sprite;
		private var cur : int = 0;

		public function ActionPreview() {
			container = new Sprite();
			canvas = new Bitmap();
			container.addChild(canvas);
			addChild(container);
			Tick.getInstance().tickSignal.add(handleFrame, "预览");
		}

		private function handleFrame(delta : int) : void {
			if ((last += delta) < unit) {
				return;
			}
			if (!action || !action.frameList || !action.frameList.length) {
				canvas.bitmapData = null;
				return;
			}
			last = 0;
			cur++;
			cur = cur % ArrayUtils.sum(action.frameList, "duration");
			var info : ActionFrameInfo;
			var tmp : int = cur;
			var i : int = 0;
			do {
				info = action.frameList[i++];
				tmp -= info.duration;
			} while (tmp >= 0);
			canvas.bitmapData = info.frame.getBitmapData();
			canvas.x = -info.frame.$registration.x * action.scale;
			canvas.y = -info.frame.$registration.y * action.scale;
			container.x = getPreferredWidth() / 2;
			container.y = getPreferredHeight() / 2;
			canvas.scaleX = canvas.scaleY = action.scale;
		}

		public function setAction(action : ActionInfo) : void {
			this.action = action;
		}
	}
}
